package com.newcoder.community.interceptor;

import com.newcoder.community.pojo.LoginTicket;
import com.newcoder.community.pojo.User;
import com.newcoder.community.serverce.UserService;
import com.newcoder.community.utill.CookieUtill;
import com.newcoder.community.utill.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

@Component
public class LoginTicketInterceptor implements HandlerInterceptor {
    @Autowired
    private UserService userService;
    @Autowired
    private HostHolder hostHolder;

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        hostHolder.clean();
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        User user = hostHolder.getUser();
        if(user!=null&&modelAndView!=null){
            modelAndView.addObject("loginUser",user);
        }
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String ticket=null;
        if(CookieUtill.getValue(request, "ticket")!=null){
            ticket = CookieUtill.getValue(request, "ticket");
        }

        if(ticket!=null){
            LoginTicket loginTicket = userService.findLoginTicket(ticket);
            if(loginTicket!=null&&loginTicket.getStatus()==0&&loginTicket.getExpired().after(new Date())){
                User user = userService.selectById(loginTicket.getUserId());
                hostHolder.setUsers(user);
            }
        }
        return true;
    }
}
